package com.xiaohongshu.kafkademo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.xiaohongshu.kafkademo.entity.User;
import com.xiaohongshu.kafkademo.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserService {
    
    private final UserMapper userMapper;
    
    @Transactional
    public User saveUser(User user) {
        if (user.getCreatedAt() == null) {
            user.setCreatedAt(LocalDateTime.now());
        }
        userMapper.insert(user);
        log.info("保存用户成功: {}", user);
        return user;
    }
    
    @Transactional
    public void deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            userMapper.deleteById(id);
            log.info("删除用户成功: {}", user);
        }
    }
    
    @Transactional
    public User updateUser(User user) {
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser != null) {
            userMapper.updateById(user);
            log.info("更新用户成功: {} -> {}", existingUser, user);
            return user;
        }
        return null;
    }
    
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
    
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }
    
    public Page<User> getUserPage(int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return userMapper.selectPage(page, null);
    }
    
    public List<User> searchUsers(String keyword) {
        return userMapper.findByUsernameContaining(keyword);
    }
    
    public List<User> getUsersByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        return userMapper.selectList(queryWrapper);
    }
}
